import { createContext, ReactNode, useContext, useLayoutEffect, useMemo, useReducer, useState } from "react"

export interface CurrUser {
    username?: string
    token?: string
    display_name?: string
    userid?: string
}

export interface UserAction {
    type: string
    payload?: CurrUser
}

const initialCurrentUser: CurrUser = {
    username: "",
    token: "",
}

function userReducer(state: CurrUser, action: UserAction) {
    switch (action.type) {
        case "init":
            return initialCurrentUser
        // 添加其他 case 以处理不同的用户操作
        case "updateUser": {
            const _user = action.payload || state
            localStorage.setItem("token", _user.token || "")
            return _user
        }
        default:
            console.log("Unknown action type")
            return state
    }
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
const emptyDispatch: React.Dispatch<UserAction> = () => { }
export const UserContext = createContext<CurrUser>(initialCurrentUser)
export const UserDispatchContext = createContext<React.Dispatch<UserAction>>(emptyDispatch)

export function UserContextProvider({ children }: { children: ReactNode }) {
    const [user, dispatch] = useReducer(userReducer, initialCurrentUser)

    return (
        <UserContext.Provider value={user}>
            <UserDispatchContext.Provider value={dispatch}>{children}</UserDispatchContext.Provider>
        </UserContext.Provider>
    )
}

export function useUserContext() {
    return useContext(UserContext)
}

export function useUserDispatchContext() {
    return useContext(UserDispatchContext)
}

export function updateUser(dispatch: React.Dispatch<UserAction>, user: CurrUser) {
    dispatch({ type: "updateUser", payload: user })
}
